home *** CD-ROM | disk | FTP | other *** search
/ Tricks of the Mac Game Programming Gurus / TricksOfTheMacGameProgrammingGurus.iso / CodeWarrior Lite / Metrowerks C⁄C++ Lite / Headers / STL Headers / random.cpp < prev    next >
Encoding:
C/C++ Source or Header  |  1995-04-26  |  1.5 KB  |  62 lines  |  [TEXT/MMCC]

  1. /*
  2.  *
  3.  * Copyright (c) 1994
  4.  * Hewlett-Packard Company
  5.  *
  6.  * Permission to use, copy, modify, distribute and sell this software
  7.  * and its documentation for any purpose is hereby granted without fee,
  8.  * provided that the above copyright notice appear in all copies and
  9.  * that both that copyright notice and this permission notice appear
  10.  * in supporting documentation.  Hewlett-Packard Company makes no
  11.  * representations about the suitability of this software for any
  12.  * purpose.  It is provided "as is" without express or implied warranty.
  13.  *
  14.  */
  15.  
  16. #include <stddef.h>
  17.  
  18. #define __SEED 161803398
  19.  
  20. class __random_generator {
  21. protected:
  22.     unsigned long table[55];
  23.     size_t index1;
  24.     size_t index2;
  25. public:
  26.     unsigned long operator()(unsigned long limit) {
  27.     index1 = (index1 + 1) % 55;
  28.     index2 = (index2 + 1) % 55;
  29.     table[index1] = table[index1] - table[index2];
  30.     return table[index1] % limit;
  31.     }
  32.     void seed(unsigned long j);
  33.     __random_generator(unsigned long j) { seed(j); }
  34. };
  35.  
  36. void __random_generator::seed(unsigned long j) {
  37.     size_t        i;
  38.     unsigned long k = 1;
  39.     table[54] = j;
  40.     for (i = 0; i < 54; i++) {
  41.         size_t ii = 21 * i % 55;
  42.         table[ii] = k;
  43.         k = j - k;
  44.         j = table[ii];
  45.     }
  46.     for (int loop = 0; loop < 4; loop++) {
  47.         for (i = 0; i < 55; i++)
  48.             table[i] = table[i] - table[(1 + i + 30) % 55];
  49.     }
  50.     index1 = 0;
  51.     index2 = 31;
  52. }
  53.  
  54. __random_generator rd(__SEED);
  55.  
  56. unsigned long __long_random(unsigned long limit) {
  57.     return rd(limit);
  58. }
  59.  
  60.  
  61.  
  62.